package org.epidroid.epidroid.news.ui;

import java.io.IOException;

import org.apache.commons.net.nntp.NNTPClient;
import org.apache.james.mime4j.codec.DecoderUtil;
import org.epidroid.epidroid.R;
import org.epidroid.epidroid.androsoul.engine.service.IAndroSoulServiceListener;
import org.epidroid.epidroid.news.engine.Group;
import org.epidroid.epidroid.news.engine.INewsService;
import org.epidroid.epidroid.news.engine.NewsArticle;
import org.epidroid.epidroid.news.engine.NewsService;
import org.epidroid.epidroid.news.engine.NewsServiceBinder;
import org.epidroid.epidroid.news.engine.Topic;

import android.app.ListActivity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.ScaleAnimation;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class TopicActivity extends ListActivity {

	private INewsService _service = null;

	private NNTPClient _client = null;
	private Topic _topic = null;
	private Group _group = null;
	private TopicAdapter _adapter = null;
	private TextView _titleTextView = null;
	private View _replyLayout = null;
	private EditText _replyText = null;
	private ServiceConnection _serviceConnection = null;
	private boolean _isReplying = false;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		bindWithNewsService();
	}

	@Override
	protected void onDestroy() {
		unbindService(_serviceConnection);
		super.onDestroy();
	}

	private void bindWithNewsService() {
		Intent intent = new Intent(this, NewsService.class);

		final IAndroSoulServiceListener listener = new IAndroSoulServiceListener() {
			public void dataChanged(final Message data) {
				TopicActivity.this.runOnUiThread(new Runnable() {
					public void run() {
						// Nothing to do here for the moment
					}
				});
			}
		};

		_serviceConnection = new ServiceConnection() {
			public void onServiceConnected(ComponentName name,
					IBinder servicebinder) {
				INewsService service = ((NewsServiceBinder) servicebinder)
						.getService();
				_service = service;
				Log.i(NewsActivity.LOGCAT, "Service is bound!");
				init();
			}

			public void onServiceDisconnected(ComponentName name) {
				Log.i(NewsActivity.LOGCAT, "Service has disconnected!");
			}
		};

		bindService(intent, _serviceConnection, Context.BIND_AUTO_CREATE);
	}

	public void init() {

		Intent intent = getIntent();
		String topicId = intent.getExtras().getString("topic");
		String group = intent.getExtras().getString("group");
		if (null == group) {
			Log.i(NewsActivity.LOGCAT, "Error, could not retrieve the group");
			return;
		}
		_group = _service.getGroupFromName(group);
		_topic = _service.getTopic(topicId, _group);
		// _topic.addRepliesToList();

		if (_topic.getNbArticles() == 0) {
			Log.e(NewsActivity.LOGCAT, "There is no article in the topic");
			return;
		}

		/* Retrieve the content of the root article */
		try {
			String body = _service.retrieveBody(_topic.getArticleByIndex(0));
			System.out.println(body);

			String encoding = getArticleEncoding(_topic.getArticleByIndex(0));

		} catch (IOException e) {
			Log.e(NewsActivity.LOGCAT, e.getMessage());
		}

		setContentView(R.layout.news_topic);

		_titleTextView = (TextView) findViewById(R.id.news_topic_title);
		_titleTextView.setText(DecoderUtil.decodeEncodedWords(
				_topic.getTitle(), null));

		initReplyView();

		_adapter = new TopicAdapter(this, R.layout.news_article,
				_topic.getList());
		setListAdapter(_adapter);
		_adapter.notifyDataSetChanged();

	}

	public void loadArticleBody(NewsArticle a) {
		try {
			a.setIsLoading(true);
			_adapter.notifyDataSetChanged();
			String body = _service.retrieveBody(a);
			a.setIsLoading(false);
			_adapter.notifyDataSetChanged();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	private void initReplyView() {
		_replyLayout = findViewById(R.id.news_topic_reply);
		_replyText = (EditText) findViewById(R.id.news_topic_reply_input);
		Button cancelButton = (Button) findViewById(R.id.news_topic_reply_cancel);
		Button sendButton = (Button) findViewById(R.id.news_topic_reply_send);

		cancelButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				cancelReply();
			}
		});

		sendButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO: post the news
			}
		});
	}

	/*
	 * Retrieve the text to be quoted in an article. Basically, take everything
	 * except the signature.
	 */
	private String retrieveQuotedText(NewsArticle ref) {
		String res = "On " + ref.getDate() + ", "
				+ ref.getFrom() + " wrote:\n";

		String body = ref.getBody();
		String[] lines = body.split("\n");
		for (String line : lines) {
			if (line.regionMatches(0, "-- ", 0, 3))
				break;
			if (line.length() == 0)
				continue;
			if (line.charAt(0) == '>')
				res += ">" + line + "\n";
			else
				res += "> " + line + "\n";
		}
		return res;
	}

	private String getSignature() {
		String res = "\n-- \n" + "Xavier Loginard <login_x@epita.fr>\n"
				+ "Using Epidroid\n";
		return res;
	}

	public void launchReply(NewsArticle ref) {
		_isReplying = true;
		_adapter.notifyDataSetChanged();
		// Retrieve the text that is being quoted
		String quoted = retrieveQuotedText(ref);
		_replyText.setText(quoted);
		_replyText.append(getSignature());
		_replyText.setSelection(quoted.length());

		_replyLayout.setVisibility(View.VISIBLE);
		ScaleAnimation anim = new ScaleAnimation(1f, 1f, 0.0f, 1f);
		anim.setDuration(200);
		_replyLayout.startAnimation(anim);

		_replyLayout.requestFocus();
	}

	public void cancelReply() {
		_isReplying = false;
		_adapter.notifyDataSetChanged();
		_replyText.setText("");
		ScaleAnimation anim = new ScaleAnimation(1f, 1f, 1f, 0.0f);
		anim.setDuration(200);
		anim.setAnimationListener(new AnimationListener() {

			@Override
			public void onAnimationEnd(Animation animation) {
				_replyLayout.setVisibility(View.GONE);
				_replyText.setText("");
			}

			@Override
			public void onAnimationRepeat(Animation animation) {
				// TODO Auto-generated method stub

			}

			@Override
			public void onAnimationStart(Animation animation) {
				// TODO Auto-generated method stub

			}

		});
		_replyLayout.startAnimation(anim);
	}

	public boolean isReplying() {
		return _isReplying;
	}

	public String getArticleEncoding(NewsArticle a) {
		return _service.getArticleEncoding(a);
	}
}
